<!--
 * @Author: your name
 * @Date: 2021-11-10 15:40:23
 * @LastEditTime: 2021-12-04 08:56:36
 * @LastEditors: Please set LastEditors
 * @Description: 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 * @FilePath: \li-yuwei\admin\src\views\home\personalCenter\index.vue
-->
<template>
  <div class="person-center-box">
    <div class="classify-wrapper">
      <div class="left-classify">
        <el-card class="box-card add-card">
          <div slot="header" class="clearfix">
            <span>系统概览</span>
          </div>
          <p>累计发表{{ articleNum }}篇文章</p>
          <p>累计创建了{{ classifyNum }}个分类</p>
          <p>累计创建了{{ tagNum }}个标签</p>
        </el-card>
      </div>
      <div class="right-classify">
        <el-card class="box-card all-card">
          <div slot="header" class="clearfix">
            <span>个人资料</span>
          </div>
          <el-tabs v-model="activeName">
            <el-tab-pane label="基本设置" name="first">
              <div class="avatar-box">
                <img :src="avatar" alt="" v-if="avatar" @click="showDrawer" />
                <img :src="noImg" alt="" @click="showDrawer" v-else />
              </div>
              <el-form
                :label-position="labelPosition"
                label-width="80px"
                :model="form"
              >
                <el-form-item label="用户名:">
                  <el-input v-model="form.username"></el-input>
                </el-form-item>
                <el-form-item label="邮箱:">
                  <el-input v-model="form.email"></el-input>
                </el-form-item>
              </el-form>
              <el-button type="primary" class="save-btn" @click="editUserInfo"
                >保存</el-button
              >
            </el-tab-pane>
            <el-tab-pane label="更改密码" name="second" class="edit-pwd-box">
              <div>
                <div class="left-text">原密码:</div>
                <div class="right-input">
                  <input
                    type="password"
                    v-model="oldPwd"
                    ref="oldinp"
                    placeholder="请输入原密码"
                  />
                  <i
                    class="iconfont icon-xianshimima"
                    v-if="showObj.old"
                    @click="changeState('old', 'oldinp')"
                  ></i>
                  <i
                    class="iconfont icon-buxianshimima"
                    v-else
                    @click="changeState('old', 'oldinp')"
                  ></i>
                </div>
              </div>
              <div>
                <div class="left-text">新密码:</div>
                <div class="right-input">
                  <input
                    type="password"
                    v-model="newPwd"
                    ref="newinp"
                    placeholder="请输入新密码"
                  />
                  <i
                    class="iconfont icon-xianshimima"
                    v-if="showObj.new"
                    @click="changeState('new', 'newinp')"
                  ></i>
                  <i
                    class="iconfont icon-buxianshimima"
                    v-else
                    @click="changeState('new', 'newinp')"
                  ></i>
                </div>
              </div>
              <div>
                <div class="left-text">确认密码:</div>
                <div class="right-input">
                  <input
                    type="password"
                    v-model="okpwd"
                    ref="okinp"
                    placeholder="请输入新密码"
                  />
                  <i
                    class="iconfont icon-xianshimima"
                    v-if="showObj.ok"
                    @click="changeState('ok', 'okinp')"
                  ></i>
                  <i
                    class="iconfont icon-buxianshimima"
                    v-else
                    @click="changeState('ok', 'okinp')"
                  ></i>
                </div>
              </div>
              <el-button type="primary" class="update-btn" @click="changePwd"
                >更新</el-button
              >
            </el-tab-pane>
          </el-tabs>
        </el-card>
      </div>
    </div>
    <a-drawer title="文件选择" width="800" :visible="visible" @close="onClose">
      <div class="box-card">
        <div class="input-box">
          <div class="title-input-box">
            <p>文件名称:</p>
            <a-input placeholder="请输入文件名称" v-model="title"> </a-input>
          </div>
          <div class="title-input-box">
            <p>文件类型:</p>
            <a-input placeholder="请输入文件类型" v-model="type"> </a-input>
          </div>
        </div>
        <div class="search-btn-box">
          <el-button type="primary" @click="searchFile">搜索</el-button>
          <el-button @click="result">重置</el-button>
        </div>
        <div class="upload-box">
          <el-upload
            action
            :http-request="handleUpload"
            :before-upload="beforeUpload"
          >
            <el-button>上传文件</el-button>
          </el-upload>
        </div>
      </div>
      <div class="main-card">
        <div
          style="width: 25%; max-width: 25%"
          v-for="item in fileList"
          :key="item.id"
          @click="valutionInfo(item)"
        >
          <a-card hoverable style="width: 95%">
            <img
              slot="cover"
              alt="example"
              :src="item.url"
              style="width: 100%; height: 150px"
            />
            <a-card-meta :title="item.name">
              <template slot="description"
                >上传于{{ item.lastModified }}</template
              >
            </a-card-meta>
          </a-card>
        </div>
      </div>
      <a-card>
        <div class="pageination-box">
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="pageIndex"
            :page-sizes="[8, 12, 24, 36]"
            layout="total, prev, pager, next, sizes"
            :total="total"
          >
          </el-pagination>
        </div>
      </a-card>
    </a-drawer>
  </div>
</template>

<script>
import noImg from "../../../assets/头像.webp";
import api from "../../../api";
import cookie from "js-cookie";
import NProgress from "nprogress";
import "nprogress/nprogress.css";
import { put, signatureUrl, getFileNameUUID, list } from "@/utils/oss.js";

export default {
  data() {
    return {
      userId: null,
      activeName: "first",
      articleNum: 0,
      classifyNum: 0,
      tagNum: 0,
      noImg,
      avatar: "",
      labelPosition: "left",
      oldPwd: "", //旧密码
      newPwd: "", //新密码
      okpwd: "", //确认新密码
      username: "",
      visible: false, //抽屉
      fileList: [],
      pageSize: 8,
      pageIndex: 1,
      type: "",
      title: "",
      //显隐密码
      showObj: {
        old: false,
        new: false,
        ok: false,
      },
      form: {
        username: "",
        email: "",
      },
    };
  },
  methods: {
    beforeUpload(file) {
      return true;
    },
    async handleUpload(option) {
      NProgress.start();
      // // 获取文件的后缀名
      var obj = option.file.name;
      var index = obj.lastIndexOf(".");
      obj = obj.substring(index, obj.length);
      // 生成的文件名，保留文件后缀名，进行拼接
      let objName = getFileNameUUID() + option.file.name;
      // 调用 ali-oss 中的方法,flieName是存放的文件夹名称，可自己定义
      await put(`flieName/${objName}`, option.file).then((res) => {
        console.log(res);
        // 上传成功之后，转换真实的地址
        signatureUrl(`flieName/${objName}`).then((res) => {
          console.log(res);
        });
      });
      NProgress.done();
      await this.getOssFile();
      this.$message({
        type: "success",
        message: "上传成功",
      });
    },
    async getOssFile() {
      //显示加载进度条--->提示用户加载进度
      NProgress.start();
      const res = await list();
      console.log(res);
      this.fileList = res.objects;
      //结束用户加载进度
      this.fileList.sort((a, b) => {
        return new Date(b.lastModified) - new Date(a.lastModified);
      });
      this.fileList = this.fileList.map((item) => {
        return {
          ...item,
          name: item.name.split("flieName/")[1],
          path: item.name,
          type: "image/" + item.name.split(".")[1],
        };
      });
      let newList = this.fileList;
      this.total = newList.length;
      if (this.title) {
        newList = newList.filter((item) => item.name.includes(this.title));
      }
      if (this.type) {
        newList = newList.filter((item) => item.type.includes(this.type));
      }
      this.fileList = newList.slice(
        (this.pageIndex - 1) * this.pageSize,
        this.pageSize * this.pageIndex
      );
      this.total = newList.length;
      NProgress.done();
    },
    // //改每页条数时
    handleSizeChange(val) {
      this.pageSize = val;
      this.getOssFile();
    },
    //改变页码时
    handleCurrentChange(val) {
      this.pageIndex = val;
      this.getOssFile();
    },
    //搜索事件
    searchFile() {
      this.pageIndex = 1;
      this.getOssFile();
    },
    //一级抽屉打开
    showDrawer() {
      this.visible = true;
    },
    //一级抽屉关闭
    onClose() {
      this.visible = false;
    },
    //赋值cover封面信息
    valutionInfo(data) {
      this.avatar = data.url;
      this.onClose();
    },
    //获取用户信息
    async getUserInfo() {
      const res = await api.getUserInfo({ id: this.userId });
      if (res.success) {
        this.form.email = res.data.email;
        this.form.username = res.data.username;
        this.avatar = res.data.avatar;
      } else {
        this.$message({
          type: "warning",
          message: "请求失败",
        });
      }
    },
    //修改用户信息
    async editUserInfo() {
      console.log(this.userId);
      const res = await api.editUserInfo({
        id: this.userId,
        username: this.form.username,
        email: this.form.email,
        avatar: this.avatar,
      });
      if (res.success) {
        this.getUserInfo();
        this.$message({
          type: "success",
          message: "用户信息已保存",
        });
      } else {
        this.$message({
          type: "warning",
          message: "请求失败",
        });
      }
    },
    //获取个数
    async getEachNum() {
      const article = await api.getArticleTotal();
      const classify = await api.getClassifyTotal();
      const tag = await api.getTagTotal();
      this.articleNum = article.data;
      this.classifyNum = classify.data;
      this.tagNum = tag.data;
    },
    //是否显示
    changeState(type, dom) {
      this.showObj[type] = !this.showObj[type];
      //切换input框状态
      if (this.showObj[type]) {
        this.$refs[dom].type = "text";
      } else {
        this.$refs[dom].type = "password";
      }
    },
    //修改密码
    async changePwd() {
      if (this.newPwd === this.okpwd) {
        const res = await api.changePassword({
          username: this.username, //用户名
          oldPwd: this.oldPwd, //旧密码
          newPwd: this.newPwd, //新密码
        });
        if (res.data.res) {
          this.$message({
            type: "success",
            message: "修改成功 请重新登录",
          });
          //清空本地存储
          window.sessionStorage.removeItem("userData");
          //删除cookie
          cookie.remove("token");
          //跳转
          this.$router.push("/login");
        } else {
          this.$message({
            type: "warning",
            message: res.data,
          });
        }
      } else {
        this.$message({
          type: "warning",
          message: "两次密码不一致",
        });
      }
    },
  },
  created() {
    const userData = JSON.parse(window.localStorage.getItem("userData"));
    //保存用户名
    this.username = userData.username;
    this.userId = userData.id;
    this.getUserInfo();
    this.getEachNum();
    this.getOssFile();
  },
};
</script>

<style lang="scss" scoped>
.classify-box {
  width: 100%;
  height: 100%;
}
.classify-wrapper {
  width: 95%;
  margin: 0 auto;
  display: flex;
  .right-classify {
    flex: 1;
  }
}
.text {
  font-size: 14px;
}

.item {
  margin-bottom: 18px;
}

.clearfix:before,
.clearfix:after {
  display: table;
  content: "";
}
.clearfix:after {
  clear: both;
}

.add-card {
  width: 630px;
  margin-top: 20px;
  margin-right: 15px;
  p {
    border-bottom: 1px solid rgb(238, 238, 238);
    padding: 18px 20px;
  }
  p:nth-last-of-type(1) {
    border: none;
  }
  .el-card__body {
    padding: 0;
  }
}
.all-card {
  width: 100%;
  margin-top: 20px;
}
.el-tab-pane {
  width: 100%;
}
.avatar-box {
  width: 100%;
  display: flex;
  justify-content: center;
  margin-bottom: 20px;
  img {
    width: 70px;
    height: 70px;
    border-radius: 50%;
  }
}
.save-btn,
.update-btn {
  padding: 8px 16px;
  border-radius: 2px;
  background-color: #0188fb;
}
.save-btn:hover,
.update-btn:hover {
  background-color: #29a2ff;
}
.update-btn {
  margin-top: 15px;
}
.edit-pwd-box > div {
  display: flex;
  align-items: center;
  .left-text {
    width: 20%;
  }
  > div {
    margin: 15px 0;
  }
}
.right-input {
  flex: 1;
  display: flex;
  align-items: center;
  border: 1px solid #ccc;
  padding: 6px 10px;
  input {
    flex: 1;
    border: none;
    outline: none;
  }
  // @if (input: foucs) {
  // }
  i {
    margin-left: 5px;
    font-size: 12px;
    cursor: pointer;
  }
}
.box-card {
  .input-box {
    margin-bottom: 20px;
    display: flex;
    align-items: center;
  }
}
.input-box .title-input-box {
  display: flex;
  align-items: center;
  p {
    width: 95px;
  }
}
.search-btn-box {
  display: flex;
  align-items: center;
  justify-content: flex-end;
  margin-bottom: 20px;
}
.main-card {
  width: 100%;
  background-color: #fff;
  display: flex;
  flex-wrap: wrap;
  padding: 20px;
  .ant-card {
    padding: 20px;
    border: none;
    margin: 5px;
    margin-top: 20px;
    margin-bottom: 20px;
  }
}
.pageination-box {
  display: flex;
  justify-content: flex-end;
}
.info-box {
  font-size: 12px;
  margin: 15px 0;
  color: #000;
}
.copy-link {
  display: flex;
  margin-bottom: -30px;
  span {
    width: 55px;
    flex-shrink: 0;
    flex-wrap: wrap;
  }
  p {
    width: 510px;
    flex-shrink: 0;
    border: 1px solid #ccc;
    padding: 5px;
  }
}
.upload-box {
  display: flex;
  justify-content: flex-end;
}
</style>
